package com.ambimmort.shj.service.policybank;

import cn.net.greenet.common.db_service.BaseDao;
import cn.net.greenet.common.policy_service.PolicySupport;
import cn.net.greenet.db.bean.Policyrepositoryinstance;
import cn.net.greenet.db.bean.Policyrepositorytype;
import cn.net.greenet.user.operation.UserPolicyBankAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;

/**
 * Created by Administrator on 2015/7/31.
 */
@Service
public class PolicybankService {
//    @Autowired
//    private SessionFactory hibernateSessionFactory;
    ResultSet rs =null;
    BaseDao baseDao = null;

    private void init() {
        baseDao = new BaseDao();
    }

    private void close() {
        if (baseDao != null) {
            baseDao.close();
        }
    }

    /**
     *
     * @param type 创建策略仓库类型名称
     * @param instance 创建策略仓库实例名称

     */
    public void createDomain(String type,String instance) throws Throwable {
        System.out.println("type::"+type+" instance::"+instance);


        PolicySupport.getInstance().getApi().createRepository(type, instance);
        String username = null;


        init();
//        Session session = hibernateSessionFactory.openSession();
//        session.clear();
//        Transaction tx = session.beginTransaction();
        try {
            String sql = "select * from Policyrepositoryinstance where instanceName='"+instance
                    +"' and PolicyRepositoryType_messageType='"+type+"'";
            Object [] params = {};
            JSONObject obj = new JSONObject();
            rs = baseDao.executeSQL(sql, params);
            if (!rs.next()) {
                Object [] param = {type,instance};
                String sql1 = "insert into Policyrepositoryinstance (PolicyRepositoryType_messageType,instanceName) values (?, ?)";
                baseDao.executeUpdate(sql1, param);
            }
//            Policyrepositorytype pt = (Policyrepositorytype) session.get(Policyrepositorytype.class, type);
//            Policyrepositoryinstance bean = new Policyrepositoryinstance(pt, instance);
//            session.saveOrUpdate(bean);
//            tx.commit();
//            UserPolicyBankAction.createPolicyBank(username, instance, type);  //写入用户创建策略仓库日志
        } catch (Exception e) {
            e.printStackTrace();
//            tx.rollback();
        } finally {
            close();
//            session.close();
        }
    }

    /**
     *
     * @param id 创建策略仓库类型名称
     * @param type 创建策略仓库类型名称
     * @param instance 创建策略仓库实例名称
     * @throws Throwable
     */
    public void deleteDomain(String id,String type,String instance) throws Throwable {

        String username = null;
        System.out.println("aaaaa|||"+username);

//        Session session = hibernateSessionFactory.openSession();
//        session.clear();
        init();
//        Transaction tx = null;
        try {

            //delete DPIEndPointBean_has_PolicyRepositoryInstance
//            BaseDao baseDao = new BaseDao();
            baseDao.executeUpdate("delete FROM DPIEndPointBean_has_PolicyRepositoryInstance where PolicyRepositoryInstance_id = ?", new Object[]{id});
            System.out.println("删除策略仓库与DPI的关系");

            //delete versionmanaged
            baseDao.executeUpdate("delete FROM versionmanaged where PolicyRepositoryInstance_id = ?", new Object[]{id});
            System.out.println("删除策略与 versionmanaged 的关系");

            //delete versionreported
            baseDao.executeUpdate("delete FROM versionreported where PolicyRepositoryInstance_id = ?", new Object[]{id});
            System.out.println("删除策略与 versionreported 的关系");

            //delete policysynchronizationitem
            ResultSet rs3 = baseDao.executeSQL("select PolicySynchronization_id from policysynchronizationitem where PolicyRepositoryInstance_id = ?", new Object[]{id});
            long PolicySynchronization_id = 0;
            while (rs3.next()) {
                PolicySynchronization_id = rs3.getLong("PolicySynchronization_id");
            }

            baseDao.executeUpdate("delete FROM policysynchronization where id = ?", new Object[]{PolicySynchronization_id});
            System.out.println("删除策略与 policysynchronization 的关系");

            baseDao.executeUpdate("delete FROM policysynchronizationitem where PolicySynchronization_id = ?", new Object[]{id});
            System.out.println("删除策略与 policysynchronizationitem 的关系");

            String sql = "select * from Policyrepositoryinstance where instanceName='"
                    +instance+"' and PolicyRepositoryType_messageType='"+type
                    +"' and id="+id;
            Object [] params = {};
            JSONObject obj = new JSONObject();
            rs = baseDao.executeSQL(sql, params);
            if (rs.next()) {
                String sql1 = "delete from Policyrepositoryinstance where instanceName='"+instance
                        +"' and PolicyRepositoryType_messageType='"+type
                        +"'and id="+id;
                baseDao.executeUpdate(sql1, params);
            }
//            Policyrepositoryinstance bean = (Policyrepositoryinstance) session.get(Policyrepositoryinstance.class, Integer.parseInt(id));
//            tx = session.beginTransaction();
//            session.delete(bean);
//            tx.commit();

            UserPolicyBankAction.deletePolicyBank(username, instance, type);  //写入用户删除策略仓库日志
        } catch (Exception e) {
            e.printStackTrace();
//            tx.rollback();
        } finally {
            close();
//            session.close();
        }
    }

    /**
     *
     * @param messageType
     * @throws Throwable
     */

    public String listDomain(String messageType)  {
        System.out.println("==listDomain=="+messageType);
        init();

//        Session session = hibernateSessionFactory.openSession();
//        session.clear();

        try {
            Policyrepositoryinstance bean = null;
            java.util.List l =null;
            Object[] params ={messageType};
//            Query q = session.createQuery("SELECT pri FROM Policyrepositoryinstance AS pri where pri.policyrepositorytype.messageType=:messageType");
//            rs=baseDao.executeSQL("select u.id,u.instanceName,u.PolicyRepositoryType_messageType from Policyrepositoryinstance as u  left join policyrepositorytype a on a.messageType=?",params);
                rs=baseDao.executeSQL("select pri.instanceName,pri.id,pri.PolicyRepositoryType_messageType from Policyrepositoryinstance AS pri where PolicyRepositoryType_messageType=?",params);
//            rs=baseDao.executeSQL("select id as id32_,PolicyRepositoryType_messageType as PolicyRe2_32_,instanceName as instance3_32_,reserved1 as reserved4_32_,reserved2 as reserved5_32_ from policyrepositoryinstance where PolicyRepositoryType_messageType=?'",params);
//            q.setParameter("messageType", messageType);
//            java.util.List l = q.list();
            JSONArray jSONArray = new JSONArray();
            while (rs.next()) {

                JSONObject jSONObject = new JSONObject();
                jSONObject.put("policy_warehouse_name",rs.getString("instanceName"));
                jSONObject.put("policy_warehouse_id", rs.getInt("id"));
                jSONObject.put("policy_warehouse_desc", PolicySupport.getInstance().getApi().getHeadVersion(messageType, rs.getString("instanceName")));
                jSONArray.add(jSONObject);
            }

//            for (int i = 0; i < l.size(); i++) {
//                bean = (Policyrepositoryinstance) l.get(i);
//                JSONObject jSONObject = new JSONObject();
//                jSONObject.put("policy_warehouse_name", bean.getInstanceName());
//                jSONObject.put("policy_warehouse_id", bean.getId() + "");
//                jSONObject.put("policy_warehouse_desc", PolicySupport.getInstance().getApi().getHeadVersion(messageType, bean.getInstanceName()) + "");
//                jSONArray.add(jSONObject);
//            }
//            try {
                return jSONArray.toString();
            } catch (Exception e) {
                return "[]";
            }

//        } catch (Exception e) {
//            e.printStackTrace();
//            return "[]";
//        }
        finally {
            close();
//            out.close();
//            session.close();
        }
    }
}
